package com.btm.distrb.comment;

import com.btm.distrb.config.MysqlConfig;
import com.btm.distrb.model.AllDB;
import com.btm.distrb.model.DBInfo;
import org.apache.commons.lang.StringUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class TableComment {

    private MysqlConfig mysqlConfig;
    private final static String tableComment = "SELECT TABLE_NAME,TABLE_COMMENT FROM information_schema.TABLES WHERE table_schema=";

    public void showTableComment(AllDB allDB) {
        DBInfo dbInfo = allDB.getStdDB();
        MysqlConfig config = new MysqlConfig();
        config.setUrl(dbInfo.getUrl());
        config.setUserName(dbInfo.getUserName());
        config.setPassword(dbInfo.getPassword());
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            Connection connection = config.getConnection();
            if (null == connection) {
                throw new SQLException("not sql connection.");
            }
            StringBuffer sql = new StringBuffer(tableComment + "'" + dbInfo.getCatalog() + "'");
            String[] prefix = allDB.getPrefix();
            if (null != prefix && 0 < prefix.length) {
                sql.append(" and (");
                for (int i = 0; i < prefix.length; i++) {
                    if (i != 0) {
                        sql.append(" or ");
                    }
                    sql.append("table_name like '" + prefix[i] + "%'");
                }
                sql.append(")");
            }
            preparedStatement = connection.prepareStatement(sql.toString());
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                System.out.println("[" + resultSet.getString("TABLE_NAME") + "]:" + resultSet.getString("TABLE_COMMENT"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
        }
    }

}
